<?php

require_once 'classes/photos.php';
require_once 'classes/albums.php';
require_once 'api/wikimapia.php';
require_once 'classes/mySession.php';

$currentAlbumid = "";
$currentAlbumLabel = "";
$photos = array();
#CHECK SESSION TO USER ALREADY LOGGED IN
#IF NOT, REDIRECT TO LOGIN PAGE
if(!$pgSession->isUserLoggedIn()){
	$pgSession->redirect("./login.php");
}
#IF YES:
else{
	$ownerN = $pgSession->getUserId();
	
	if(isset($_GET["".Album::$currentAlbumForms])){
		$currentAlbumid = $_GET["".Album::$currentAlbumForms];
	}
	
	if(isset($_GET["".Album::$currentAlbumLabelForms])){
		$currentAlbumLabel = $_GET["".Album::$currentAlbumLabelForms];
	}
	
	if(isset($_POST["newphoto"]) && trim($_POST["newphoto"])==='1'){
		
		$uploadDate = new DateTime();
		
		$numberFiles = count($_FILES["uploadedPhotos"]["tmp_name"]);
		if (!file_exists("./photos/" . $ownerN)) {
			mkdir("./photos/" . $ownerN);
		}
		
		$fileNameBase = $ownerN . "_".$uploadDate->format('-Y-m-d-H-i-s-')."_";
		$uploadResults = array();
		$wikiMapiaApi = new WikimapiaAPI();
		for ($i=0;$i<$numberFiles;$i++){
			
			$fileNameN = $_FILES["uploadedPhotos"]["name"][$i];
			$tmpFileNameN = $_FILES["uploadedPhotos"]["tmp_name"][$i];
			$file_nameN =  "./photos/". $ownerN ."/" .$fileNameBase.$fileNameN;
			
			move_uploaded_file($tmpFileNameN,$file_nameN);
			
			$pUtils = new PhotoUtils();
			
			$pUtils->createThumbnail("./photos/". $ownerN ."/", $fileNameBase.$fileNameN);
			
			if(file_exists($file_nameN)){
				list($width, $height, $type, $attr) = getimagesize($file_nameN);
				$textN = NULL;
				if(isset($_POST["text"])){
					$textN = $_POST["text"];
				}else if(isset($_GET["text"])){
					$textN = $_GET["text"];
				}
				
				$p = new Photo(NULL, $ownerN, $currentAlbumid,($fileNameBase.$fileNameN),$uploadDate->format('Y-m-d H:i:s'));
				$p->setOriginal_file_name($fileNameN);
				$p->setText($textN);
				$p->setWidth($width);
				$p->setHeight($height);
				$exif = exif_read_data($file_nameN, 0, true);
				if(!is_null($exif)){
					$exifUtils = new ExifUtils($exif);
					$p->setDate_taken($exifUtils->getEXIFDateTime());
					$p->setDate_gps($exifUtils->getGPSDateTime());
					$p->setLatitude($exifUtils->getCoordinateLatitude());
					$p->setLongitude($exifUtils->getCoordinateLongitude());
				}
				
				$resp = $photoUtils->savePhoto($p);
				$p = $resp["photo"];
				$lat = $p->getLatitudeDecimal();
				$lng = $p->getLongitudeDecimal();
				if(!(is_null($lat) || is_null($lng))){
					$wikiObj = $wikiMapiaApi->getObjectsInPoint($lat,$lng);
					$geoAlbuns = WikimapiaAPI::getGeoAlbuns($wikiObj);
					
					$albumUtils->saveGeoAlbuns($geoAlbuns);
					$ids = array(0=>$p->getId());
					$photoUtils->savePhotoInGeoAlbuns($ids,$geoAlbuns);
				}
			}
		}
	}
	
	$photosResp = $photoUtils->findUserPhotos($ownerN, $currentAlbumid, -1);
	$albumsResp = $albumUtils->findUserAlbums($ownerN, -1);
	if($photosResp["status"]){
		$photos = $photosResp["photos"];
	}
	
	if($albumsResp["status"]){
		$albums = $albumsResp["albums"];
	}
}


#	BUILD HEADER
#	CONNECT TO DATABASE
#	CHECK IF THERE IS AN ALBUM ID ON THE POST SESSION FIELD
#		IF YES, LIST PHOTOS FROM ALBUMS (PUT + BUTTON)
#		IF NOT, LIST ALL AlBUMS (PUT + BUTTON)

?>

<html lang="pt-BR">
<head>
	<title>PG++ :: Ferramenta de Anotação de Localização em Fotografias</title>
	<meta charset="utf-8">
	<meta name="description" content="Ferramenta de anotação de localização em coleções de fotografias pessoais.">
	<meta name="author" content="Davi Serrano e George Henrique">
	<script src="lib/jquery.js"></script>
	<script src="lib/jquery-ui.js"></script>
	
	<link rel="stylesheet" href="css/reset.css">
	<link rel="stylesheet" href="css/styles.css">
	<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>
	
</head>

<body>

	<header>
		<div class="topo">
			<a href="./"><img class="logo left" src="images/logo.png"/></a>
			<nav class="nav-topo">
				<a href="./home.php">Mapa</a>
				<a href="./album.php">Álbuns</a>
				<a href="./geoAlbum.php">Geo-Álbuns</a>
				<a href="./photo.php">Fotos</a>
				<a href="./logout.php">Logout</a>
			</nav>
			
			<div class="clear"></div>
		</div>
	</header>
	
	<div class="clear"></div>
	
	<section>
		<div class="conteudo">
			<h1></h1>
			
			<div class="topo-caixa">
				<span class="titulo"><?php echo $currentAlbumLabel.(empty($currentAlbumLabel)?"Todas as Fotos":"");?></span>
				<form method="post" enctype="multipart/form-data" action="./photo.php?<?php echo Album::$currentAlbumForms."=".$currentAlbumid."&".Album::$currentAlbumLabelForms."=".$currentAlbumLabel;?>" id="uploadPhotosForm"  class="novo-album">
					<input type="file" style="visibility:hidden;" name="uploadedPhotos[]" onchange="checkSize()" id="uploadedPhotosId" multiple="multiple" accept="image/gif, image/jpeg, image/png, image/jpg, image/x-png, image/pjpeg">
					<input type="hidden" name="newphoto" value="1" />
					<?php if(!empty($currentAlbumLabel)){?><input type="button" id="submitUpload" onclick="callUploadWindow()" value="Enviar Fotos"/><?php }?>
				</form>
			</div>
			
			<div class="caixa">
				<?php foreach ($photos as $photoRow){
					$photo = $photoUtils->photoFromRow($photoRow);
				?>
				<div class="imagem">
					<a href="./consulta.php?photoid=<?php echo $photo->getId();?>" class="ver-foto">
						<img style="max-width: 100%; max-height: 100%;" src="<?php echo $photo->getURL();?>"/>
					</a>
				</div>
				<?php
					}
				?>
				
				<!-- <div class="navegacao">
					<a href="#" class="voltar"><< Voltar</a>
					<a href="#" class="numero">1</a>
					<a href="#" class="numero">2</a>
					<a href="#" class="numero ativo">3</a>
					<a href="#" class="numero">4</a>
					<a href="#" class="numero">5</a>
					<a href="#" class="avancar">Avançar >></a>
					<div class="clear"></div>
				</div> -->
				
				<div class="clear"></div>
			</div>
			
			<div class="clear"></div>
		</div>
	</section>
	
	<div class="clear"></div>
	
	<footer>
		<nav class="rodape">
			<a href="#">SOBRE</a>
			<a href="#">CONTATO</a>
		</nav>
	</footer>
	
	<div class="fundo"></div>
	<div class="overlap">
		<div class="caixa-foto">
			<p class="bold font-14">Álbum: <a href="#" id="albumLink" class="regular laranja">Vilarejos da Argentina</a></p>
			<div class="foto">
				<img style="height: 100%; max-width: 100%; margin: auto; display: block;" src="images/default.jpg"/>
			</div>
			<p class="bold font-14">Descrição:<br>
				<textarea rows="3" cols="50" maxlength="255" readonly="readonly" class="descricao" id="descricaoText"></textarea>
				<input type="button" hidden="true" onclick="setAlbumCover()" id="albumCoverButton" class="editar" value="Capa do Álbum"/>
				<a href="#" onclick="editData()" id="photoDataButton" class="editar">Editar</a>
			</p>
		</div>
		<div class="caixa-localizacao">
			<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3.exp&libraries=places"></script>
			<div style="overflow:hidden;height:348px;width:278px;">
				<input type="text" id="pac-input" class="controls" placeholder="Busca">
				<div id="gmap_canvas" style="height:348px;width:278px;"></div>
				<style>#gmap_canvas img{max-width:none!important;background:none!important}</style>
				<!-- <a class="google-map-code" href="http://www.map-embed.com" id="get-map-data">www.map-embed.com</a> -->
			</div>
			<input type="hidden" id="currentPhotoid" />
			<script type="text/javascript" src="js/pg_googleMapsViewPhoto.js"></script>
			<a href="#" onclick="editLocation()" id="locationButton" class="alterar">Alterar localização</a>
		</div>
		
		<div class="clear"></div>
	</div>
	
<script>
	$(function() {	
		$(".ver-foto").click(function() {
			event.preventDefault();
			var link = $(this).attr('href');

			$.ajax({
				url: link,
				type: "GET",
				dataType: "json",
				async: false,
				success: function(data) {
					$(".fundo").fadeIn();
					$(".overlap").center();
					$(".overlap").fadeIn();
					change(data);
				},
				error: function(data) {
					console.log(data);
				}
			});
		});		
		
		$(".fundo").click(function() {
			$(".fundo").fadeOut();
			$(".overlap").fadeOut();
		});
	});

	function checkSize(){
		var file_list = document.getElementById("uploadedPhotosId").files;
		var maxSize = 31*1024*1024;
		var filesSize = 0;
		for (var i = 0, file; file = file_list[i]; i++) {
			filesSize+=file.size;
		}
		if(filesSize>maxSize){
			alert("Tamanho máximo de upload excedido: 30MB");
		}else{
			document.getElementById("uploadPhotosForm").submit();
		}
	}

	function callUploadWindow(){
		document.getElementById("uploadedPhotosId").click();
	}

	function setAlbumCover(){
		var pid = document.getElementById("currentPhotoid").value;
		var urlEncoded = "./add_albumCover.php?photoid="+encodeURIComponent(pid)+"&<?php echo Album::$currentAlbumForms."=".$currentAlbumid?>";
		$.ajax({
			url: urlEncoded,
			type: "GET",
			dataType: "json",
			async: false,
			success: function(data) {
				if(data.status){
					document.getElementById("albumCoverButton").hidden = true;
				}else{
					alert("Não foi possível salvar. Tente novamente mais tarde");
				}
			},
			error: function(data) {
				console.log(data);
			}
		});
	}
		

	function editData(){
		if(document.getElementById("descricaoText").readOnly){
			document.getElementById("descricaoText").readOnly=false;
			document.getElementById("photoDataButton").innerHTML="Salvar";
		}else{
			var photoid = document.getElementById("currentPhotoid").value;
			var text = document.getElementById("descricaoText").value;
			var urlEncoded = "./add_description.php?description="+encodeURIComponent(text)+"&photoid="+photoid;
			$.ajax({
				url: urlEncoded,
				type: "GET",
				dataType: "json",
				async: false,
				success: function(data) {
					if(data.status){
						document.getElementById("descricaoText").readOnly=true;
						document.getElementById("photoDataButton").innerHTML="Editar";
					}else{
						alert("Não foi possível salvar. Tente novamente mais tarde");
					}
				},
				error: function(data) {
					console.log(data);
				}
			});
		}
	}
	
	function change(data) {
		$(".foto img").attr("src", "./photos/"+data.owner+"/"+data.file_name);
		document.getElementById("descricaoText").value = (data.text?data.text:"");
		document.getElementById("albumCoverButton").hidden = data.cover==data.file_name;
		document.getElementById("albumLink").innerHTML = (data.label);
		document.getElementById("albumLink").href = "./photo.php?<?php echo Album::$currentAlbumForms;?>="+data.albumid+"&<?php echo Album::$currentAlbumLabelForms; ?>="+data.label;
		document.getElementById("currentPhotoid").value = data.id;
		document.getElementById("locationButton").innerHTML = ('Alterar Localização');
		if(photoMarker) photoMarker.setDraggable(false);
		if(infowindow) infowindow.close();
		if(!map){
			init_map(data.latitude, data.longitude);
		}else{
			
			if(data.latitude && data.latitude!=0 && data.longitude && data.longitude!=0){ 
				var position = new google.maps.LatLng(data.latitude, data.longitude);
				map.setCenter(position);
				map.setZoom(13);
				photoMarker.setMap(map);
				photoMarker.setPosition(position);
			}else{
				map.setZoom(0);
				map.setCenter(new google.maps.LatLng(0, 0));
				photoMarker.setMap(null);
			}
		}
	}
	
	jQuery.fn.center = function () {
		this.css("position","absolute");
		this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + 
													$(window).scrollTop()) + "px");
		this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + 
													$(window).scrollLeft()) + "px");
		return this;
	}
</script>
</body>
</html>
